package com.zzw.controller;

import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * UEditor控制器
 * 用于处理UEditor富文本编辑器的上传请求
 */
@Controller
@RequestMapping("/ueditor")
public class UEditorController {

    /**
     * 获取UEditor配置信息
     */
    @RequestMapping("/config")
    public void config(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        String action = request.getParameter("action");
        System.out.println("UEditor请求action= " + action);

        // 根据action参数执行不同操作
        if (action == null || "config".equals(action)) {
            // 返回配置信息
            // UEditor服务器端配置
            String configStr = "{\n" +
                    "    \"imageActionName\": \"uploadimage\",\n" +
                    "    \"imageFieldName\": \"upfile\",\n" +
                    "    \"imageMaxSize\": 2048000,\n" +
                    "    \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                    "    \"imageCompressEnable\": true,\n" +
                    "    \"imageCompressBorder\": 1600,\n" +
                    "    \"imageInsertAlign\": \"none\",\n" +
                    "    \"imageUrlPrefix\": \"\",\n" +
                    "    \"imagePathFormat\": \"/ueditor/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                    "    \"fileActionName\": \"uploadfile\",\n" +
                    "    \"fileFieldName\": \"upfile\",\n" +
                    "    \"filePathFormat\": \"/ueditor/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                    "    \"fileUrlPrefix\": \"\",\n" +
                    "    \"fileMaxSize\": 51200000,\n" +
                    "    \"fileAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                    "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                    "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                    "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                    "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                    "    ],\n" +
                    "    \"videoActionName\": \"uploadvideo\",\n" +
                    "    \"videoFieldName\": \"upfile\",\n" +
                    "    \"videoPathFormat\": \"/ueditor/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                    "    \"videoUrlPrefix\": \"\",\n" +
                    "    \"videoMaxSize\": 102400000,\n" +
                    "    \"videoAllowFiles\": [\n" +
                    "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                    "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"\n" +
                    "    ]\n" +
                    "}";

            String callback = request.getParameter("callback");
            PrintWriter writer = response.getWriter();
            if (callback != null) {
                writer.write(callback + "(" + configStr + ")");
            } else {
                writer.write(configStr);
            }
            writer.flush();
            writer.close();
        } else if ("uploadimage".equals(action)) {
            Gson gson = new Gson();
            // 处理上传图片请求
            try {
                MultipartFile upfile = null;
                if (request instanceof org.springframework.web.multipart.MultipartHttpServletRequest) {
                    org.springframework.web.multipart.MultipartHttpServletRequest multipartRequest =
                        (org.springframework.web.multipart.MultipartHttpServletRequest) request;
                    upfile = multipartRequest.getFile("upfile");
                }

                if (upfile != null && !upfile.isEmpty()) {
                    // 文件存储路径: 项目根路径/upload/image/日期
                    String uploadPath = request.getSession().getServletContext().getRealPath("/upload/image/");
                    String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
                    File dir = new File(uploadPath + File.separator + datePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    // 生成唯一文件名
                    String originalFilename = upfile.getOriginalFilename();
                    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                    String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

                    // 保存文件
                    File targetFile = new File(dir, filename);
                    upfile.transferTo(targetFile);

                    // 文件访问URL
                    String url = request.getContextPath() + "/upload/image/" + datePath + "/" + filename;

                    // 构建返回结果
                    Map<String, Object> result = new HashMap<>();
                    result.put("state", "SUCCESS");
                    result.put("url", url);
                    result.put("title", filename);
                    result.put("original", originalFilename);

                    // 返回JSON结果
                    response.getWriter().write(gson.toJson(result));
                } else {
                    Map<String, Object> result = new HashMap<>();
                    result.put("state", "文件为空");
                    response.getWriter().write(gson.toJson(result));
                }
            } catch (Exception e) {
                e.printStackTrace();
                Map<String, Object> result = new HashMap<>();
                result.put("state", "上传失败: " + e.getMessage());
                response.getWriter().write(gson.toJson(result));
            }
        } else if ("uploadfile".equals(action)) {
            Gson gson = new Gson();
            // 处理上传文件请求
            try {
                MultipartFile upfile = null;
                if (request instanceof org.springframework.web.multipart.MultipartHttpServletRequest) {
                    org.springframework.web.multipart.MultipartHttpServletRequest multipartRequest =
                        (org.springframework.web.multipart.MultipartHttpServletRequest) request;
                    upfile = multipartRequest.getFile("upfile");
                }

                if (upfile != null && !upfile.isEmpty()) {
                    // 文件存储路径: 项目根路径/upload/file/日期
                    String uploadPath = request.getSession().getServletContext().getRealPath("/upload/file/");
                    String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
                    File dir = new File(uploadPath + File.separator + datePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    // 生成唯一文件名
                    String originalFilename = upfile.getOriginalFilename();
                    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                    String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

                    // 保存文件
                    File targetFile = new File(dir, filename);
                    upfile.transferTo(targetFile);

                    // 文件访问URL
                    String url = request.getContextPath() + "/upload/file/" + datePath + "/" + filename;

                    // 构建返回结果
                    Map<String, Object> result = new HashMap<>();
                    result.put("state", "SUCCESS");
                    result.put("url", url);
                    result.put("title", filename);
                    result.put("original", originalFilename);

                    // 返回JSON结果
                    response.getWriter().write(gson.toJson(result));
                } else {
                    Map<String, Object> result = new HashMap<>();
                    result.put("state", "文件为空");
                    response.getWriter().write(gson.toJson(result));
                }
            } catch (Exception e) {
                e.printStackTrace();
                Map<String, Object> result = new HashMap<>();
                result.put("state", "上传失败: " + e.getMessage());
                response.getWriter().write(gson.toJson(result));
            }
        } else {
            Gson gson = new Gson();
            // 不支持的action
            Map<String, Object> result = new HashMap<>();
            result.put("state", "不支持的action: " + action);
            response.getWriter().write(gson.toJson(result));
        }
    }

    /**
     * 处理图片上传
     */
    @RequestMapping("/uploadimage")
    @ResponseBody
    public Map<String, Object> uploadImage(MultipartFile upfile, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (upfile != null && !upfile.isEmpty()) {
                // 文件存储路径: 项目根路径/upload/image/日期
                String uploadPath = request.getSession().getServletContext().getRealPath("/upload/image/");
                String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
                File dir = new File(uploadPath + File.separator + datePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 生成唯一文件名
                String originalFilename = upfile.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

                // 保存文件
                File targetFile = new File(dir, filename);
                upfile.transferTo(targetFile);

                // 文件访问URL
                String url = request.getContextPath() + "/upload/image/" + datePath + "/" + filename;

                // 构建返回结果
                result.put("state", "SUCCESS");
                result.put("url", url);
                result.put("title", filename);
                result.put("original", originalFilename);
            } else {
                result.put("state", "文件为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("state", "上传失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 处理文件上传
     */
    @RequestMapping("/uploadfile")
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile upfile, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (upfile != null && !upfile.isEmpty()) {
                // 文件存储路径: 项目根路径/upload/file/日期
                String uploadPath = request.getSession().getServletContext().getRealPath("/upload/file/");
                String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
                File dir = new File(uploadPath + File.separator + datePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 生成唯一文件名
                String originalFilename = upfile.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

                // 保存文件
                File targetFile = new File(dir, filename);
                upfile.transferTo(targetFile);

                // 文件访问URL
                String url = request.getContextPath() + "/upload/file/" + datePath + "/" + filename;

                // 构建返回结果
                result.put("state", "SUCCESS");
                result.put("url", url);
                result.put("title", filename);
                result.put("original", originalFilename);
            } else {
                result.put("state", "文件为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("state", "上传失败: " + e.getMessage());
        }

        return result;
    }
}
